// pages/code/code.js
const app = getApp()

Page({
  onLoad: function(){
    let url = app.globalData.userInfo.qrCode;
    if(url != null){
      let host = app.globalData.host
      this.setData({
        codeUrl: host + "/" + url
      })
    }
   
  },

  /**
   * 页面的初始数据
   */
  data: {
    codeUrl: null
  },

  chooseImage: function () {
    let self = this
    let token = wx.getStorageSync('token')

    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        console.log(res)
        let host = app.globalData.host

        wx.uploadFile({
          url: host + '/item/image',
          filePath: res.tempFilePaths[0],
          name: 'image',
          success: (res)=>{
            let realRes = JSON.parse(res.data)
            let hostUrl = realRes.data

            wx.request({
              url: host + '/user/qrCode',
              method: 'POST',
              header: {
                'authorization': token,
                'content-type': 'application/x-www-form-urlencoded'
              },
              data: {
                qrCode: hostUrl
              },
              success: (res)=>{
                app.globalData.userInfo.qrCode = res.data.data
                self.setData({
                  codeUrl: host +"/" + res.data.data
                })
              }
            })
          },
          error: function(e){
            console.error(e)
          }
        })
      },
      fail: (e)=>{
        console.error(e)
      }
    });
  },

  preview: function (e) {
    
    let url = this.data.codeUrl
    let urls = [url]
    wx.previewImage({
      urls: urls,
      current: url,
      success: function () {
        console.log("preview")
      },
      fail: function (e) {
        console.log(e)
      }
    })
  },
})